﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace StandardManager.EntityCode
{
    public partial class FieldSelectorForm : Form
    {
        private DataTable m_dt;
        public string[] SelectedFields { get; set; }

        public string CodeFieldName { get; set; }

        public FieldSelectorForm(DataTable dt, string[] oldSelectedFields, string codeName)
        {
            InitializeComponent();
            m_dt = dt;
            SelectedFields = oldSelectedFields;
            txtFieldName.Text = string.IsNullOrEmpty(codeName) ? txtFieldName.Text : codeName;
            InitializeListBox();
            UpdateFieldsSelectedStatus();
        }

        private void InitializeListBox()
        {
            this.lstData.SelectionMode = SelectionMode.One;
            this.lstData.DoubleClick += LstData_DoubleClick;

            this.lstData.Items.Clear();
            this.lstCombine.Items.Clear();

            foreach (DataColumn column in m_dt.Columns)
            {
                lstData.Items.Add(column.ColumnName);
            }
        }

        private void UpdateFieldsSelectedStatus()
        {
            if (SelectedFields != null && SelectedFields.Length > 0)
            {
                foreach (var selectedField in SelectedFields)
                {
                    this.lstCombine.Items.Add(selectedField);
                    this.lstData.Items.Remove(selectedField);
                }
            }
        }

        private void LstData_DoubleClick(object? sender, EventArgs e)
        {
            button3_Click(sender, e);
        }

        private void button3_Click(object sender, EventArgs e)
        {
            if (lstData.SelectedItem != null)
            {
                string selectedItem = lstData.SelectedItem.ToString();
                lstCombine.Items.Add(selectedItem);
                lstData.Items.Remove(selectedItem);
            }
        }

        private void button4_Click(object sender, EventArgs e)
        {
            InitializeListBox();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            SelectedFields = new string[lstCombine.Items.Count];
            lstCombine.Items.CopyTo(SelectedFields, 0);
            CodeFieldName = txtFieldName.Text;
            this.DialogResult = DialogResult.OK;
            this.Close();
        }

        private void button2_Click(object sender, EventArgs e)
        {
            this.DialogResult = DialogResult.Cancel;
            this.Close();
        }
    }
}
